<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>进阶篇-vuex的使用,计算器实现</title>
    <script src="../js/lib/vue.min.js"></script>
    <script src="../js/lib/vuex.js"></script>
</head>
<body>
<div id="app">
    <div class="result">{{result}}</div>
    <div class="enter">{{enter===''?0:enter}}</div>
    <div class="keys">
        <div class="list">
            <!--键盘区域-->
            <keyboard v-for="item in keys" :value="item"></keyboard>
        </div>
    </div>
</div>
<script>
    const store=new Vuex.Store({
        state:{
            result:'',//运算结果
            enter:''//输入的值
        },
        //定义名为calculate的mutation
        mutations:{
            calculate(state,value){
                if(value === '='){
                    state.result = eval(state.enter);
                    state.enter +=value;
                }else if(value ==='clear'){
                    state.result= state.enter='';
                }else {
                    state.enter += value;
                }
            }
        }
    });
    //定义keyboard
    Vue.component('keyboard',{
        //接受的参数value，代表键盘输入的值
        props:['value'],
        //模板
        template:'<div :data-value="value">{{value}}</div>',
        methods:{
            getKeyboardValue(event){
                let value=event.target.dataset.value;
                this.$store('calculate',value);
            }
        }
    });

    //创建vue实例
    const app=new Vue({
        el:'#app',
        store,
        //给store添加处理方法
        computed:{
            result(){
                //通过this.$store获取仓库的数据result
                return this.$store.state.result;
            },
            enter(){
                return this.$store.state.enter;
            }
        },
        data:{
            //16个按键的值
            keys:[
                'clear', '+', '-', '*',
                '7', '8', '9', '/',
                '4', '5', '6', '0',
                '1', '2', '3', '=',
            ]
        }
    });
</script>
</body>
</html>